﻿using System;
using System.Diagnostics;
using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using Windows.Devices.Geolocation;

namespace TrackingLocation
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        Geolocator tracking;
        
        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        static ScheduledAgent()
        {
            // Subscribe to the managed exception handler
            Deployment.Current.Dispatcher.BeginInvoke(delegate
            {
                Application.Current.UnhandledException += UnhandledException;
            });
        }

        /// Code to execute on Unhandled Exceptions
        private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                Debugger.Break();
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            //TODO: Add code to perform your task in background
            if (tracking == null)
            {
                tracking = new Geolocator();
                tracking.DesiredAccuracy = PositionAccuracy.High;
                tracking.MovementThreshold = 100; // 100 meters
                tracking.StatusChanged += geolocator_StatusChanged;
                tracking.PositionChanged += geolocator_PositionChanged;
            }
            //ShellToast toast = new ShellToast();
            //toast.Content = "Test Background Agents";
            //toast.Title = "Location: ";
            //// toast.NavigationUri = new Uri("/MainPage.xaml", UriKind.Relative);
            //toast.Show();
            //ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(10));
            NotifyComplete();
        }
        private void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
        {
           // string positionString = this.GetCoordinateString(args.Position.Coordinate);
           // ShellToast toast = new ShellToast();
           // toast.Content = positionString;
           // toast.Title = "Location: ";
           //// toast.NavigationUri = new Uri("/MainPage.xaml", UriKind.Relative);
           // toast.Show();
        }

        private void geolocator_StatusChanged(Geolocator sender, StatusChangedEventArgs args)
        {
            switch (args.Status)
            {
                case PositionStatus.Disabled:
                    // the application does not have the right capability or the location master switch is off
                    break;

                case PositionStatus.Initializing:
                    // the geolocator started the tracking operation
                    break;

                case PositionStatus.NoData:
                    // the location service was not able to acquire the location
                    break;

                case PositionStatus.Ready:
                    // the location service is generating geopositions as specified by the tracking parameters
                    break;

                case PositionStatus.NotAvailable:
                    // not used in WindowsPhone, Windows desktop uses this value to signal that there is no hardware capable to acquire location information
                    break;

                case PositionStatus.NotInitialized:
                    // the initial state of the geolocator, once the tracking operation is stopped by the user the geolocator moves back to this state
                    break;
            }
            // IMPORTANT: the event handler is called on a worker thread,
            // so we must use the Dispatcher to update the UI from the main thread
        }
        private string GetCoordinateString(Geocoordinate coordinate)
        {
            string positionString = string.Format("Lat: {0:0.0000}, Long: {1:0.0000}, Acc: {2}m",
                        coordinate.Latitude, coordinate.Longitude, coordinate.Accuracy);
            return positionString;
        }
    }
}